package repository

import (
	"n-server/internal/model"

	"gorm.io/gorm"
)

type UserRepository interface {
	Greate(user *model.User) error                                           // 创建用户
	Delete(id uint) error                                                    // 删除用户
	Update(user *model.User) error                                           // 更新用户
	GetById(id uint) (*model.User, error)                                    // 根据 ID 查询
	GetByEmail(email string) (*model.User, error)                            // 根据邮箱查询
	GetByName(name string) (*model.User, error)                              // 根据用户名查询
	List(offset, limit int, sort, order string) ([]model.User, int64, error) // 查询用户列表
}

type userRepositoryImpl struct {
	db *gorm.DB
}

// NewUserRepository 创建 UserRepository 实例
func NewUserRepository(db *gorm.DB) UserRepository {
	return &userRepositoryImpl{db: db}
}

func (r *userRepositoryImpl) Greate(user *model.User) error {
	return r.db.Create(user).Error
}

func (r *userRepositoryImpl) Delete(id uint) error {
	return r.db.Delete(&model.User{}, id).Error
}

func (r *userRepositoryImpl) Update(user *model.User) error {
	return r.db.Save(user).Error
}

func (r *userRepositoryImpl) GetById(id uint) (*model.User, error) {
	var user model.User
	err := r.db.First(&user, id).Error
	return &user, err
}

func (r *userRepositoryImpl) GetByEmail(email string) (*model.User, error) {
	var user model.User
	err := r.db.Where("email = ?", email).First(&user).Error
	return &user, err
}

func (r *userRepositoryImpl) GetByName(name string) (*model.User, error) {
	var user model.User
	err := r.db.Where("username = ?", name).First(&user).Error
	return &user, err
}

func (r *userRepositoryImpl) List(offset, limit int, sort, order string) ([]model.User, int64, error) {
	var users []model.User
	var total int64

	err := r.db.Model(&model.User{}).Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	query := r.db.Offset(offset).Limit(limit)

	// 处理排序
	if sort != "" {
		// 验证排序字段，防止 SQL 注入
		vaildSortFields := map[string]bool{
			"id":         true,
			"name":       true,
			"email":      true,
			"role":       true,
			"status":     true,
			"created_at": true,
			"updated_at": true,
		}

		if vaildSortFields[sort] {
			orderClause := sort
			if order == "desc" {
				orderClause += " DESC"
			} else {
				orderClause += " ASC"
			}
			query = query.Order(orderClause)
		} else {
			// 默认按创建时间倒序
			query = query.Order("created_at DESC")
		}
	}

	err = query.Find(&users).Error
	return users, total, err
}
